//
//  HYOriginalViewController.m
//  KaiJing
//
//  Created by lanou on 16/1/14.
//  Copyright © 2016年 HuangZuCui. All rights reserved.
//

#import "HYOriginalViewController.h"
#import "CJOriginalTableViewCell.h"
#import "HYMoreShortModel.h"
#import "PKRequestManager.h"
#import "PKMusicPlayer.h"
#import "CJPictorialCellWebViewViewController.h"
#import "UMSocial.h"
#import <MJRefresh.h>
#import <MBProgressHUD.h>
#import "SZBaseNavController.h"
@interface HYOriginalViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *originalTableView;
@property (nonatomic, strong) NSMutableArray *sourceArray;    //数据源

@property (nonatomic, strong) PKMusicPlayer *player;   //播放器
@property (nonatomic, strong) NSMutableArray *array;  //歌曲
@property (nonatomic, assign) NSInteger index;  //记录上次播放的音乐坐标
@property (nonatomic, assign) NSInteger nowIndex;  //正在播放的
@property (nonatomic, strong) NSTimer *timer;   //定时器

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation HYOriginalViewController




//电影原声
- (void)viewDidLoad {
    [super viewDidLoad];
     self.navigationItem.title = @"电影原声";
    self.view.backgroundColor = kRandomClolor;
    _sourceArray = [NSMutableArray array];
    _page = 1;

    //定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerPlay) userInfo:nil repeats:YES];
    

    [self requestData];
    [self hudMore];
    [self addTableView];
    _player = [PKMusicPlayer sharedPlayer];
    _array = [NSMutableArray array];
    
    //刷新
    self.originalTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
      
        [self requestData];
      
    }];
    
    self.originalTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        _page += 1;
        [self requestData];
        
    }];
}


//菊花
-(void)hudMore
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    _hud.frame = self.view.bounds;
    _hud.labelText = @"休息一下";
    _hud.minSize = CGSizeMake(100, 100);
    _hud.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_hud];
    [_hud show:YES];
}

- (void)requestData {
    
    //http://morguo.com/forum.php?mod=threadmusic&androidflag=1&appfrom=ios&iosversion=3.13&page=1
    NSString *urlStr = [NSString stringWithFormat:@"http://morguo.com/forum.php?mod=threadmusic&androidflag=1&appfrom=ios&iosversion=3.13&page=%ld",_page];
    [PKRequestManager requestWithUrlString:urlStr parDic:nil method:GET finish:^(NSDictionary *dataDic) {
        [_hud hide:YES];
        
        if (_page == 1) {
            [_sourceArray removeAllObjects];
            [_array removeAllObjects];
        }
        
        NSArray *array = dataDic[@"data"][@"list"];
        for (NSDictionary *dic in array) {
            HYMoreShortModel *model = [[HYMoreShortModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_sourceArray addObject:model];
            [_array addObject:model.musicurl];
        }

        [self.originalTableView.mj_footer endRefreshing];
        [self.originalTableView.mj_header endRefreshing];
        
        _player.musicArray = _array;
        [self.originalTableView reloadData];
    } error:^(NSError *error) {
        
    }];
  
}

- (void)addTableView {
    
    _originalTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kTabBarHeight) style:(UITableViewStylePlain)];
    _originalTableView.dataSource = self;
    _originalTableView.delegate = self;
    [self.view addSubview:_originalTableView];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _sourceArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *identifier = @"CJOriginalTableViewCell";
    CJOriginalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[CJOriginalTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (_player.index == indexPath.row && _player.isPlaying) {
        cell.openButton.selected = YES;
        [self imageButtonRoate:cell.imageButton];
    } else {
        cell.openButton.selected = NO;
    }
    HYMoreShortModel *model = _sourceArray[indexPath.row];
    cell.model = model;
    
    //播放
    cell.openButton.tag = 2200 + indexPath.row;
    [cell.openButton addTarget:self action:@selector(clickImageButton:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.imageButton.tag = 2300 + indexPath.row;
    
    
   // NSInteger tid = [model.tid integerValue];
    //点赞
    cell.bottomView.praiseButton.tag = 13000 + indexPath.row;
    [cell.bottomView.praiseButton addTarget:self action:@selector(praiseButton:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.bottomView.moreButton.tag = 14000 + indexPath.row;
    [cell.bottomView.moreButton addTarget:self action:@selector(moreButton:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    
    return cell;
    
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [CJOriginalTableViewCell cellOfContentLabelHeight:_sourceArray[indexPath.row]];
    
    return height + 300;
}


//点击播放音乐
- (void)clickImageButton:(UIButton *)button {
    

    
    button.selected = !button.selected;
    NSInteger num = button.tag - 2200;

    
    
    //点击播放或暂停
    if (button.selected) {
        [_player changeMusicWithIndex:num];
    } else {
        [_player pause];
    }

    
    //判断是不是上一首
    if (num != _index) {
        
        //改变上一首button的状态
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_index inSection:0];
        CJOriginalTableViewCell *cell = [_originalTableView cellForRowAtIndexPath:indexPath];
        cell.openButton.selected = !cell.openButton.selected;
    }
    //记录当前的标
    _index = _player.index;
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_index inSection:0];
    CJOriginalTableViewCell *cell = [_originalTableView cellForRowAtIndexPath:indexPath];
    
    [self imageButtonRoate:cell.imageButton];

}



- (void)timerPlay {
 
    if (_player.currentTime == _player.finishTime && _player.finishTime != 0) {
        [_player finishPlay];
    }
    
    if (_index != _player.index && _player.isPlaying) {
        //改变上一首button的状态
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_index inSection:0];
        CJOriginalTableViewCell *cell = [_originalTableView cellForRowAtIndexPath:indexPath];
        cell.openButton.selected = !cell.openButton.selected;
        
        //改变正在播放的button的状态
        NSIndexPath *indexPathn = [NSIndexPath indexPathForRow:_player.index inSection:0];
        CJOriginalTableViewCell *celln = [_originalTableView cellForRowAtIndexPath:indexPathn];
        celln.openButton.selected = !celln.openButton.selected;
   
        _index = _player.index;
        
        [self imageButtonRoate:celln.imageButton];
        
    }
}




//实现转动的方法
- (void)imageButtonRoate:(UIButton *)button
{
   
    if (button.tag - 2300 == _player.index && _player.isPlaying) {
        [UIView animateWithDuration:0.1 animations:^{
            
            //改变视图的弧度
            button.transform = CGAffineTransformRotate(button.transform, M_PI_4 / 10);
            
        }completion:^(BOOL finished) {
            
            //转完后再转一次
            
            [self imageButtonRoate:button];
            
        }];
    
    }

}



- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    if (indexPath.row != _player.index) {
//        
//        CJOriginalTableViewCell *myCell = (CJOriginalTableViewCell *)cell;
//        
//        [UIView animateWithDuration:0.1 animations:^{
//            
//            //改变视图的弧度
//            myCell.imageButton.transform = CGAffineTransformRotate(myCell.imageButton.transform, 0);
//        
//            
//        }completion:^(BOOL finished) {
//            
//        }];
//    }
//

    for (id oneLayer in cell.layer.sublayers) {
        
        if ([oneLayer isKindOfClass:NSClassFromString(@"CJOriginalTableViewCell")]) {
            
            [oneLayer removeFromSuperlayer];
            
        }
        
    }

    
    
}


//cell将要放进重用池
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CJOriginalTableViewCell *myCell = (CJOriginalTableViewCell *)cell;
    
    [self imageButtonRoate:myCell.imageButton];
    
    
}

//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CJPictorialCellWebViewViewController *webViewVC = [[CJPictorialCellWebViewViewController alloc] init];
    
    HYMoreShortModel *model = _sourceArray[indexPath.row];
    webViewVC.tid = model.tid;
    
    [self.navigationController pushViewController:webViewVC animated:YES];
  
}

//视图将要消失
- (void)viewWillDisappear:(BOOL)animated {
    
    [_timer invalidate];
}



//点赞
- (void)praiseButton:(UIButton *)button {
    
    
    // 是否登录userName isEqualToString:@"YES"]
    if ([SZLoginTool shareLogin].isLogin) {
        
        button.selected = !button.selected;
        
        NSString *isLike = nil;
        if (button.selected) {
            isLike = @"like";
        } else {
            isLike = @"unlike";
        }
        
        
        
        HYMoreShortModel *model = _sourceArray[button.tag - 13000];
        
        NSString *str = [NSString stringWithFormat:@"http://morguo.com/forum.php?mod=threadlikecp&op=%@&tid=%@&formhash=%@&androidflag=1&appfrom=ios&iosversion=3.13",isLike,model.tid, [SZLoginTool shareLogin].formhash];
        
        [PKRequestManager requestWithUrlString:str parDic:nil method:GET finish:^(NSDictionary *dataDic) {
            if (dataDic[@"data"][@"result"]) {
                SZLog(@"点赞成功");
                
                model.isliked = button.selected;
            } else {
                SZLog(@"点赞失败");
                button.selected = !button.selected;
            }
            
            
        } error:^(NSError *error) {
            button.selected = !button.selected;
            
        }];
        
    } else {
        
        SZLoginViewController *loginVC = [[SZLoginViewController alloc] init];
        SZBaseNavController *loginNav = [[SZBaseNavController alloc] initWithRootViewController:loginVC];
        [self presentViewController:loginNav animated:YES completion:nil];
        
        
    }
}

//分享
- (void)moreButton:(UIButton *)button {
    
   
    HYMoreShortModel *model = _sourceArray[button.tag - 14000];
    
    NSString *url = [NSString stringWithFormat:@"http://morguo.com/forum.php?mod=viewthread&tid=%@&isfrommobile=1",model.tid];
    
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIViewController *viewController = window.rootViewController;
    [UMSocialSnsService presentSnsIconSheetView:viewController
                                         appKey:@"569ee21fe0f55a76b10021e3"
                                      shareText:[NSString stringWithFormat:@"<<%@>>详情点击%@",model.subject,url]
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToEmail,UMShareToWechatFavorite,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToTencent,nil]
                                       delegate:nil];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
